package com.zam.web.courseController;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zam.comment.Result;
import com.zam.pojo.Course;
import com.zam.service.ICourseService;
import com.zam.utils.IntegralUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zam.service.ICourseUserService;
import com.zam.pojo.CourseUser;

import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.server.PathParam;

import static com.zam.comment.Constants.CODE_500;

/******************************
 controller层
 ******************************/
@RestController
@RequestMapping("/CU")
public class CourseUserController {
    @Autowired
    private ICourseUserService courseUserService;

    @Autowired
    private ICourseService courseService;

    /*
    添加数据
    */
    @PostMapping
    public boolean save(@RequestBody CourseUser courseUser) {
        return courseUserService.saveOrUpdate(courseUser);
    }

    /*
    删除数据
    */
    @DeleteMapping("/{id}")
    public Boolean delete(@PathVariable Integer id) {
        return courseUserService.removeById(id);
    }

    /*
    删除多个数据
    */
    @DeleteMapping("/del/batch")
    public boolean deleteBatch(@RequestBody List<Integer> ids) {
        return courseUserService.removeByIds(ids);
    }

    /*
     查看全部
    */
    @GetMapping
    public List<CourseUser> findAll() {
        return courseUserService.list();
    }

    /*
    根据id查看
    */
    @GetMapping("/{id}")
    public CourseUser findOne(@PathVariable Integer id) {
        return courseUserService.getById(id);
    }

    /*
    分页查询
     */
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize, Course course, HttpServletRequest request) {
        //获取token，当Redis中的key
        String token = request.getHeader("token");
        String userIdStr = JWT.decode(token).getAudience().get(0);
        int userId = Integer.parseInt(userIdStr);
        LambdaQueryWrapper<CourseUser> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(CourseUser::getUserId, userId);
        //根据userId查询课程id
        List<Integer> collect = courseUserService.list(queryWrapper1).stream().map(CourseUser::getCourseId).collect(Collectors.toList());

        LambdaQueryWrapper<Course> queryWrapper = new LambdaQueryWrapper<>();
        if (course.getFileName() != null && !course.getFileName().isEmpty()) {
            queryWrapper.like(Course::getFileName, course.getFileName());
        }
        if (course.getFileType() != null && !course.getFileType().isEmpty()) {
            queryWrapper.like(Course::getFileType, course.getFileType());
        }
        if (course.getFileUserId() != null && !course.getFileUserId().isEmpty()) {
            queryWrapper.eq(Course::getFileUserId, course.getFileUserId());
        }
        queryWrapper.in(Course::getId, collect);
        return Result.success(courseService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

    /*
       在收藏中添加数据
     */
    @GetMapping("/update")
    public Result update(@RequestParam String fileName, @RequestParam String fileUserId, HttpServletRequest request) {
        //获取token，当Redis中的key
        String token = request.getHeader("token");
        String userIdStr = JWT.decode(token).getAudience().get(0);
        int userId = Integer.parseInt(userIdStr);

        //根据课程名和用户id查询课程id
        LambdaUpdateWrapper<Course> queryWrapper = new LambdaUpdateWrapper<>();
        queryWrapper.eq(Course::getFileName, fileName);
        queryWrapper.eq(Course::getFileUserId, fileUserId);
        Course one = courseService.getOne(queryWrapper);
        Integer id = one.getId();
        //判断是否收藏
        LambdaQueryWrapper<CourseUser> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(CourseUser::getUserId, userId).eq(CourseUser::getCourseId,id);
        CourseUser isCourseController = courseUserService.getOne(queryWrapper1);
        if(BeanUtil.isNotEmpty(isCourseController)){
            return Result.error(CODE_500,"已收藏 ! ! !");
        }
        //同步修改积分
        synchronized (this){
            //积分修改,积分-20
            Boolean isUseIntegral = IntegralUtil.useIntegral(userId);
            if(!isUseIntegral){
                return Result.error(CODE_500,"积分不足");
            }
            //被收藏用户积分+10
            IntegralUtil.collectIntegral(Integer.parseInt(fileUserId));
        }

        //修改收藏数量，用于热门推荐
        int coullectCount=0;
        if (!StrUtil.isEmpty(one.getCollectCount())){
            coullectCount = Integer.parseInt(one.getCollectCount());
        }
        queryWrapper.set(Course::getCollectCount, coullectCount + 1);
        courseService.update(queryWrapper);  //修改收藏数量

        //添加收藏记录
        CourseUser courseUser = new CourseUser();
        courseUser.setCourseId(id);
        courseUser.setUserId(userId);
        courseUserService.removeByCU(courseUser);   //手动删除
        courseUserService.save(courseUser);

        return Result.success("收藏成功");
    }

    //取消收藏
    @GetMapping("/noCollect")
    public Result update(@RequestParam String fileId, HttpServletRequest request) {
        String token = request.getHeader("token");
        String userIdStr = JWT.decode(token).getAudience().get(0);
        int userId = Integer.parseInt(userIdStr);
        CourseUser courseUser = new CourseUser();
        courseUser.setCourseId(Integer.parseInt(fileId));
        courseUser.setUserId(userId);
        courseUserService.removeByCU(courseUser);
        return Result.success();
    }
}

